package com.uum.admin.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.uum.admin.pojo.entity.SysUser;
import com.uum.admin.service.SysUserService;
import com.uum.common.core.annotation.Operation;
import com.uum.common.core.constant.RedisConstants;
import com.uum.common.core.enums.BusinessType;
import com.uum.common.core.result.Result;
import com.uum.common.core.result.ResultCode;
import com.uum.common.core.valid.InsertGroup;
import com.uum.web.util.IpUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

@Api(tags = "门户用户接口")
@RestController
@RequestMapping("/api/v2/users")
@RequiredArgsConstructor
public class WebController {

    private final SysUserService sysUserService;
    private final RedisTemplate redisTemplate;

    @ApiOperation(value = "注册用户")
    @PostMapping("/register")
    public Result register(@Validated(InsertGroup.class) @RequestBody SysUser user) {
        boolean result = sysUserService.register(user);
        return Result.judge(result);
    }

    @ApiOperation(value = "校验用户名是否存在")
    @GetMapping("/checkName/{username}")
    public Result checkName(@PathVariable String username) {
        SysUser user = sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(StrUtil.isNotBlank(username), SysUser::getUsername, username));
        boolean isExist = user == null;
        return Result.success(isExist ? "邮箱可用" : "邮箱已存在").add("isExist", isExist);
    }

    @ApiOperation(value = "激活账号")
    @GetMapping("/activeUser/{token}")
    public Result activeUser(@PathVariable String token) {
        boolean result = sysUserService.activeUser(token);
        return Result.judge(result, "激活成功", "激活失败");
    }

    @ApiOperation(value = "重新获取激活码")
    @GetMapping("/afreshActive/{username}")
    public Result afreshActive(@PathVariable String username) {
        String key = "reacquire::" + username;
        if (redisTemplate.hasKey(key)) {
            Long expire = redisTemplate.getExpire(key);
            return Result.failed(ResultCode.USER_SEND_EMAIL_TIME_OVER,expire);
        }
        boolean result = sysUserService.afreshActive(username);
        if (result) {
            redisTemplate.opsForValue().set(key, 1, 1, TimeUnit.MINUTES);
        }
        return Result.judge(result, "已重新发送至邮箱", "发送失败，请稍后重试");
    }

    @ApiOperation(value = "记录首页访问次数(PV)")
    @GetMapping("/index")
    public void index(HttpServletRequest request) {
        String ip = IpUtils.getIpAddr(request);
        String key = RedisConstants.WEB_PV + DateUtil.today();
        //判断该缓存是否有该ip
        boolean hasKey = redisTemplate.opsForHash().hasKey(key, ip);
        if (hasKey) {
            //有的话，说明之前该ip访问过，次数加1
            redisTemplate.opsForHash().increment(key, ip, 1);
        } else {
            //没有，说明第一次访问，给该ip计数1次
            redisTemplate.opsForHash().put(key,ip,1);
            redisTemplate.expire(key,26,TimeUnit.HOURS);
        }
    }

}
